import { SignJWT, jwtVerify } from "jose";

const alg = "HS256";
const secretKey = new TextEncoder().encode(process.env.secret);
const expiresIn = process.env.expiresIn || "24h";
const issuer = "zengsun";

/**
 * Signs a JSON Web Token (JWT) with the provided payload.
 *
 * @param {Object} payload - The payload to be included in the JWT.
 * @return {Promise<string>} - A promise that resolves to the signed JWT.
 */
export async function signJWT(payload) {
  return await new SignJWT(payload)
    .setProtectedHeader({ alg })
    .setIssuer(issuer)
    .setExpirationTime(expiresIn)
    .sign(secretKey);
}

/**
 * Verifies a JSON Web Token (JWT) and returns its payload.
 *
 * @param {string} token - The JWT to be verified.
 * @return {Object} The payload of the verified JWT.
 */
export async function verifyJWT(token) {
  const { payload } = await jwtVerify(token, secretKey, {
    issuer,
  });
  return payload;
}
